﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.DBUtility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Web;
using Ultimus.WFServer;

namespace H2.NET.Web.Workflow.Helper
{
    public static class TaskHelper
    {
        private static readonly string connectionString = PubConstant.GetConnectionString("bpmDB");

        private static string GetINITIATEID(string key, string processName)
        {
            if (HttpContext.Current.Session[key] == null)
            {
                DbHelperSQL.connectionString = connectionString;
                var result =
                    DbHelperSQL.GetSingle("select INITIATEID from INITIATE where PROCESSNAME = '" + processName + "'");

                return result == null ? "" : result.ToString();
            }
            else
            {
                return HttpContext.Current.Session[key].ToString();
            }
        }

        /// <summary>
        /// 新开门店流程实例号
        /// </summary>
        public static string NEW_STORE_APPLICATION_TASKID
        {
            get
            {
                return GetINITIATEID("NEW_STORE_APPLICATION_TASKID", "New Store Application").Trim();
            }
        }

        /// <summary>
        /// 主数据变更流程实例号
        /// </summary>
        public static string STORE_DATA_CHANGE_TASKID
        {
            get
            {
                return GetINITIATEID("STORE_DATA_CHANGE_TASKID", "Store Data Change").Trim();
            }
        }

        /// <summary>
        /// 保证金变更流程实例号
        /// </summary>
        public static string STORE_DEPOSIT_CHANGE_TASKID
        {
            get
            {
                return GetINITIATEID("STORE_DEPOSIT_CHANGE_TASKID", "Store Deposit Change").Trim();
            }
        }
        /// <summary>
        /// 保证金收取流程实例号
        /// </summary>
        public static string STORE_DEPOSIT_RECEIVE_TASKID
        {
            get
            {
                return GetINITIATEID("STORE_DEPOSIT_RECEIVE_TASKID", "Store Deposit Receive").Trim();
            }
        }

        /// <summary>
        /// 新保证金收取流程实例号
        /// </summary>
        public static string NEW_STORE_DEPOSIT_RECEIVE_TASKID
        {
            get
            {
                return GetINITIATEID("NEW_STORE_DEPOSIT_RECEIVE_TASKID", "New Store Deposit Receive").Trim();
            }
        }
        public static string MDC_ITSS_TASKID
        {
            get
            {
                return GetINITIATEID("MDC_ITSS_TASKID", "MDC Itss").Trim();
            }
        }


        public static string GetNameByAutoKey(string key)
        {
            var result = string.Empty;
            if (key == Constant.PROCESS_STORE)
            {
                result = "门店开店/升级/翻新/续签";
            }
            else if (key == Constant.PROCESS_CHANGEDEALER)
            {
                result = "经销商更换";
            }
            else if (key == Constant.PROCESS_CHANGELEVEL)
            {
                result = "门店关闭/降级";
            }
            else if (key == Constant.PROCESS_DEVICEISSUED)
            {
                result = "设备发放";
            }
            else if (key == Constant.PROCESS_TRANSFER)
            {
                result = "设备三方转移";
            }
            else if (key == Constant.PROCESS_CHANGESTATUS)
            {
                result = "设备报废/库存";
            }
            else if (key == Constant.PROCESS_CHANGEOTHER)
            {
                result = "其他信息更改";
            }
            else if (key == Constant.PROCESS_MDCITSS)
            {
                result = "驳回流程申请";
            }

            return result;
        }

        /// <summary>
        /// 根据流程名，实例号获取TaskID
        /// </summary>
        /// <param name="process">流程名</param>
        /// <param name="incident">实例号</param>
        /// <param name="step">步骤名，默认第一个步骤</param>
        /// <returns>TaskID</returns>
        public static Task GetTask(string process, int incident, string step = "")
        {
            var filter = new TasklistFilter
            {
                strProcessNameFilter = process,
                nIncidentNo = incident
            };

            if (step != "")
            {
                filter.strStepLabelFilter = step;
            }

            var taskList = new Tasklist();
            taskList.LoadFilteredTasks(filter);
            return taskList.GetFirstTask();
        }

        public static string GetVariableBySingleValue(this TaskAPI taskApi, string key)
        {            
            return ((object[])taskApi[key])[0].ToString();
        }

        /// <summary>
        /// 从数据库取得流程步骤处理人
        /// </summary>
        public static void SetStepRecipient(this TaskAPI TaskAPI)
        {
            var rec_a = new SortedList<string, string>();

            var rec_s = (mdc_Recipient.process == TaskAPI.Process &
                                            (mdc_Recipient.distribute == "*") &
                                            mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (mdc_Recipient rec in rec_s)
            {
                if (!rec_a.ContainsKey(rec.Step))
                {
                    rec_a.Add(rec.Step, rec.Recipient);
                    continue;
                }

                if (rec_a.Values[rec_a.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                {
                    continue;
                }


                rec_a[rec.Step] = rec_a.Values[rec_a.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
            }

            //步骤处理人赋值
            for (int i = 0; i < rec_a.Keys.Count; i++)
            {
                TaskAPI["R_" + rec_a.Keys[i].Replace(" ", "_")] = rec_a.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }

        public static void SetNewStoreApplicationRecipient(this TaskAPI TaskAPI, string region, string province)
        {
            var recA = new SortedList<string, string>();
            var recS = (mdc_Recipient.process == TaskAPI.Process & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0].Trim();
                var provinceA = distributes.Length > 1 ? distributes[1].Trim() : "*";

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(province.Trim()))
                {
                    continue;
                }

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, region.Trim().ToUpper(), StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") +
                                         rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                }
            }

            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {
                Logging.GetLogger().Info("******新开门店步骤处理人*******");
                //Add By Tony 20160419
                Logging.GetLogger().Info(TaskAPI.Process + "_" + TaskAPI.Step + "_" + TaskAPI.Incident);
                Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                Logging.GetLogger().Info("******新开门店步骤处理人*******");
                TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }

        /// <summary>
        /// 主数据变更步骤处理人
        /// </summary>
        public static void SetStoreDataChangeRecipient(this TaskAPI TaskAPI, string region, string province, string category)
        {
            var recA = new SortedList<string, string>();
            var recS = (mdc_Recipient.process == "Store Data Change" & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0];
                var categoryA = distributes.Length > 1 ? distributes[1] : "*";
                var provinceA = distributes.Length > 2 ? distributes[2] : "*";

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, region, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断变更种类
                if (!categoryA.Contains("*") && !String.Equals(categoryA, category, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(province))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                }
            }

            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {
                Logging.GetLogger().Info("******主数据变更步骤处理人*******");
                //Add By Tony 20160419
                Logging.GetLogger().Info(TaskAPI.Process + "_" + TaskAPI.Step + "_" + TaskAPI.Incident);
                Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i]);
                Logging.GetLogger().Info("******主数据变更步骤处理人*******");
                TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }

        /// <summary>
        /// 主数据变更步骤处理人
        /// </summary>
        public static void SetStoreItssRecipient(this TaskAPI TaskAPI, string region, string province, string category)
        {
            var recA = new SortedList<string, string>();
            var recS = (mdc_Recipient.process == "MDC Itss" & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0];
                var categoryA = distributes.Length > 1 ? distributes[1] : "*";
                var provinceA = distributes.Length > 2 ? distributes[2] : "*";

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, region, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断变更种类
                if (!categoryA.Contains("*") && !String.Equals(categoryA, category, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(province))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                }
            }

            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {
                Logging.GetLogger().Info("******主数据变更步骤处理人*******");
                //Add By Tony 20160419
                Logging.GetLogger().Info(TaskAPI.Process + "_" + TaskAPI.Step + "_" + TaskAPI.Incident);
                Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i]);
                Logging.GetLogger().Info("******主数据变更步骤处理人*******");
                TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }


        /// <summary>
        /// 保证金收取步骤处理人
        /// </summary>
        public static void SetDepositReceiveRecipient(this TaskAPI TaskAPI, string region, string province, string channel)
        {
            var recA = new SortedList<string, string>();
            var recS = (mdc_Recipient.process == "Store Deposit Receive" & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0];
                var provinceA = distributes.Length > 1 ? distributes[1] : "*";
                var channelA = distributes.Length > 2 ? distributes[2] : "*";

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, region, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(province))
                {
                    continue;
                }

                //判断渠道 DULUX LEVIS
                if (!channelA.Contains("*") && !String.Equals(channelA, channel, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                }
            }

            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {
                Logging.GetLogger().Info("******保证金收取步骤处理人*******");
                //Add By Tony 20160419
                Logging.GetLogger().Info(TaskAPI.Process + "_" + TaskAPI.Step + "_" + TaskAPI.Incident);
                Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                Logging.GetLogger().Info("******保证金收取步骤处理人*******");
                TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }

        /// <summary>
        /// 保证金变更步骤处理人
        /// </summary>
        public static void SetDepositChangeRecipient(this TaskAPI TaskAPI, string region, string province)
        {
            Logging.GetLogger().Info("******保证金变更步骤处理人*******");
            Logging.GetLogger().Info("region:" + region + ",province:" + province);
            var recA = new SortedList<string, string>();
            var recS = (mdc_Recipient.process == "Store Deposit Change" & mdc_Recipient.status == 1).List<mdc_Recipient>();
            foreach (var rec in recS)
            {
                if (string.IsNullOrEmpty(rec.Distribute)) continue;
                var distributes = rec.Distribute.Split('_');
                var regionA = distributes[0];
                var provinceA = distributes.Length > 1 ? distributes[1] : "*";

                //判断区域
                if (!regionA.Contains("*") && !String.Equals(regionA, region, StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                //判断省份
                if (!provinceA.Contains("*") && !provinceA.Contains(province))
                {
                    continue;
                }

                if (recA.ContainsKey(rec.Step))
                {
                    if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
                    {
                        recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
                    }
                }
                else
                {
                    recA.Add(rec.Step, rec.Recipient);
                    Logging.GetLogger().Info("recA.Add(rec.Step, rec.Recipient),rec.Step:" + rec.Step + ", rec.Recipient:" + rec.Recipient);
                }


            }

            //步骤处理人赋值
            for (int i = 0; i < recA.Keys.Count; i++)
            {

                //Add By Tony 20160419
                Logging.GetLogger().Info(TaskAPI.Process + "_" + TaskAPI.Step + "_" + TaskAPI.Incident);
                Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                Logging.GetLogger().Info("******保证金变更步骤处理人*******");
                Logging.GetLogger().Info("");
                TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            }
        }

        //public static void SetDepositChangeRecipient(string region, string province)
        //{
        //    Logging.GetLogger().Info("******保证金变更步骤处理人*******");
        //    Logging.GetLogger().Info("region:" + region + ",province:" + province);
        //    var recA = new SortedList<string, string>();
        //    var recS = (mdc_Recipient.process == "Store Deposit Change" & mdc_Recipient.status == 1).List<mdc_Recipient>();
        //    foreach (var rec in recS)
        //    {
        //        if (string.IsNullOrEmpty(rec.Distribute)) continue;
        //        var distributes = rec.Distribute.Split('_');
        //        var regionA = distributes[0];
        //        var provinceA = distributes.Length > 1 ? distributes[1] : "*";

        //        //判断区域
        //        if (!regionA.Contains("*") && !String.Equals(regionA, region, StringComparison.CurrentCultureIgnoreCase))
        //        {
        //            continue;
        //        }

        //        //判断省份
        //        if (!provinceA.Contains("*") && !provinceA.Contains(province))
        //        {
        //            continue;
        //        }

        //        if (recA.ContainsKey(rec.Step))
        //        {
        //            if (!recA.Values[recA.IndexOfKey(rec.Step)].Contains(rec.Recipient))
        //            {
        //                recA[rec.Step] = recA.Values[recA.IndexOfKey(rec.Step)] + (rec.Type == "EMAIL" ? ";" : ",") + rec.Recipient;
        //            }
        //        }
        //        else
        //        {
        //            recA.Add(rec.Step, rec.Recipient);
        //            Logging.GetLogger().Info("recA.Add(rec.Step, rec.Recipient),rec.Step:" + rec.Step + ", rec.Recipient:" + rec.Recipient);
        //        }


        //    }

        //    //步骤处理人赋值
        //    for (int i = 0; i < recA.Keys.Count; i++)
        //    {

        //        //Add By Tony 20160419
                
        //        Logging.GetLogger().Info("R_" + recA.Keys[i].Replace(" ", "_") + ":" + recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
        //        Logging.GetLogger().Info("******保证金变更步骤处理人*******");
        //        Logging.GetLogger().Info("");
        //        //TaskAPI["R_" + recA.Keys[i].Replace(" ", "_")] = recA.Values[i].Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        //    }
        //}


        /// <summary>
        /// 第一步，初始化流程(7个通用流程变量)
        /// </summary>
        /// <param name="TaskAPI"></param>
        public static void InitTask(this TaskAPI TaskAPI, t_User UserAPI, string applicationNo)
        {
            TaskAPI.UserName = UserAPI.UserName;
            TaskAPI["ApplicationNo"] = applicationNo;
            TaskAPI["ApplicatorName"] = UserAPI.UserFullName;
            TaskAPI["Applicator"] = UserAPI.UserName;
            TaskAPI["Time"] = System.DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
            TaskAPI["ApplicatorEmail"] = UserAPI.Mail;
            TaskAPI["Department"] = UserAPI.Department;
        }
        //d30.intra/svc_dpcna_mdc
        public static void InitAutoTask(this TaskAPI TaskAPI, string applicationNo)
        {
            const string autoApplicationName = "d30.intra/svc_dpcna_mdc";
            TaskAPI.UserName = autoApplicationName;
            TaskAPI["ApplicationNo"] = applicationNo;
            TaskAPI["ApplicatorName"] = autoApplicationName;
            TaskAPI["Applicator"] = autoApplicationName;
            TaskAPI["Time"] = DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss");
        }

        /// <summary>
        /// 初始化审批记录
        /// </summary>
        public static t_Assessment InitAssessment(this TaskAPI TaskAPI, t_User UserAPI)
        {
            var ass = new t_Assessment
            {
                Process = TaskAPI.Process,
                Incident = TaskAPI.Incident,
                Step = TaskAPI.Step,
                UserName = TaskAPI.UserName,
                UserFullName = TaskAPI.UserFullName,
                AssignedToUserName = UserAPI.UserName,
                AssignedToUserFullName = UserAPI.UserFullName,
                Department = UserAPI.Department,
                StartTime = TaskAPI.StartTime,
                Time = DateTime.Now,
                Opinion2 = "",
                OpinionText2 = "",
                Status = 1
            };

            var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            if (!string.IsNullOrEmpty(autoBusinessKey))
            {
                ass.BusinessProcess = autoBusinessKey;
            }
            var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
            var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
            //如果没有父流程，说明他是一个新发起的流程
            if (parentProcess == "" && parentIncident == "")
            {
                var assessment = (t_Assessment.process == ass.Process & t_Assessment.incident == ass.Incident)
                    .ListFirst<t_Assessment>();
                //如果是第一步就新建，其他的就找有的
                if (assessment != null && assessment.BusinessKey != "")
                {
                    ass.BusinessKey = assessment.BusinessKey;
                }
                else
                {
                    var key = "";
                    var num = "0001";
                    switch (ass.BusinessProcess)
                    {
                        case Constant.PROCESS_CHANGEDEALER:
                            key = "DC";
                            break;
                        case Constant.PROCESS_CHANGELEVEL:
                            key = "SD";
                            break;
                        case Constant.PROCESS_CHANGEOTHER:
                            key = "MC";
                            break;
                        case Constant.PROCESS_CHANGESTATUS:
                            key = "DD";
                            break;
                        case Constant.PROCESS_STORE:
                            key = "NS";
                            break;
                        case Constant.PROCESS_TRANSFER:
                            key = "DT";
                            break;
                        case Constant.PROCESS_MDCITSS:
                            key = "BH";
                            break;
                    }
                    var timeKey = key + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                    var ass1 = (t_Assessment.businessKey.Like(timeKey + "%")).ListFirst<t_Assessment>("BusinessKey desc");

                    if (ass1 != null)
                    {
                        var businessKey = ass1.BusinessKey;
                        var numBak = Utils.StrToInt(businessKey.Substring(businessKey.Length - 4), 0) + 1;
                        var numKey = "";
                        numKey = numBak.ToString();
                        for (var s = numBak.ToString().Length; s < 4; s++)
                        {
                            numKey = "0" + numKey;
                        }
                        timeKey += numKey;
                    }
                    else
                    {
                        timeKey += num;
                    }
                    ass.BusinessKey = timeKey;



                }
            }
            else
            {
                var assessment = (t_Assessment.process == parentProcess & t_Assessment.incident == parentIncident)
                   .ListFirst<t_Assessment>();
                ass.BusinessKey = assessment.BusinessKey;
            }

            return ass;
        }
        public static t_Assessment InitAutoAssessment(this TaskAPI TaskAPI)
        {
            var ass = new t_Assessment
            {
                Process = TaskAPI.Process,
                Incident = TaskAPI.Incident,
                Step = TaskAPI.Step,
                UserName = TaskAPI.UserName,
                UserFullName = TaskAPI.UserFullName,
                AssignedToUserName = "d30.intra/svc_dpcna_mdc",
                AssignedToUserFullName = "d30.intra/svc_dpcna_mdc",
                StartTime = TaskAPI.StartTime,
                Time = DateTime.Now,
                Opinion2 = "",
                OpinionText2 = "",
                Status = 1
            };

            var autoBusinessKey = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
            if (!string.IsNullOrEmpty(autoBusinessKey))
            {
                ass.BusinessProcess = autoBusinessKey;
            }
            var parentProcess = TaskAPI.GetVariableBySingleValue("ParentProcess");
            var parentIncident = TaskAPI.GetVariableBySingleValue("ParentIncident");
            //如果没有父流程，说明他是一个新发起的流程
            if (parentProcess == "" && parentIncident == "")
            {
                var assessment = (t_Assessment.process == ass.Process & t_Assessment.incident == ass.Incident)
                    .ListFirst<t_Assessment>();
                //如果是第一步就新建，其他的就找有的
                if (assessment != null && assessment.BusinessKey != "")
                {
                    ass.BusinessKey = assessment.BusinessKey;
                }
                else
                {
                    var key = "";
                    var num = "0001";
                    switch (ass.BusinessProcess)
                    {
                        case Constant.PROCESS_CHANGEDEALER:
                            key = "DC";
                            break;
                        case Constant.PROCESS_CHANGELEVEL:
                            key = "SD";
                            break;
                        case Constant.PROCESS_CHANGEOTHER:
                            key = "MC";
                            break;
                        case Constant.PROCESS_CHANGESTATUS:
                            key = "DD";
                            break;
                        case Constant.PROCESS_STORE:
                            key = "NS";
                            break;
                        case Constant.PROCESS_TRANSFER:
                            key = "DT";
                            break;
                        case Constant.PROCESS_MDCITSS:
                            key = "BH";
                            break;
                    }
                    var timeKey = key + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                    var ass1 = (t_Assessment.businessKey.Like(timeKey + "%")).ListFirst<t_Assessment>("BusinessKey desc");

                    if (ass1 != null)
                    {
                        var businessKey = ass1.BusinessKey;
                        var numBak = Utils.StrToInt(businessKey.Substring(businessKey.Length - 4), 0) + 1;
                        var numKey = "";
                        numKey = numBak.ToString();
                        for (var s = numBak.ToString().Length; s < 4; s++)
                        {
                            numKey = "0" + numKey;
                        }
                        timeKey += numKey;
                    }
                    else
                    {
                        timeKey += num;
                    }
                    ass.BusinessKey = timeKey;



                }
            }
            else
            {
                var assessment = (t_Assessment.process == parentProcess & t_Assessment.incident == parentIncident)
                   .ListFirst<t_Assessment>();
                ass.BusinessKey = assessment.BusinessKey;
            }

            return ass;
        }

        /// <summary>
        /// 克隆对象
        /// </summary>
        public static object CloneObject(this object o)
        {
            Type t = o.GetType();
            PropertyInfo[] properties = t.GetProperties();
            Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
            foreach (PropertyInfo pi in properties)
            {
                if (pi.CanWrite)
                {
                    object value = pi.GetValue(o, null);
                    pi.SetValue(p, value, null);
                }
            }
            return p;
        }

        /// <summary>
        /// 获取storeid
        /// </summary>
        /// <param name="queryName"></param>
        /// <returns></returns>
        public static int GetStoreId(this TaskAPI TaskAPI, string queryName)
        {
            var store_id = AksRequest.GetQueryInt(queryName);
            var blankVlue = TaskAPI.GetVariableBySingleValue("BlankVlue");
            if (!string.IsNullOrEmpty(blankVlue))
            {
                store_id = Utils.StrToInt(blankVlue, 0);
            }
            return store_id;
        }

        /// <summary>
        /// 转换成中文流程名
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string ConvertToCn(this string key)
        {
            string name = string.Empty;
            switch (key)
            {
                case "ChangeStore":
                    name = "门店主数据变更";
                    break;
                case "ChangeDevice":
                    name = "设备主数据变更";
                    break;
                case "ChangeContract":
                    name = "合同主数据变更";
                    break;
                case "DiscardDevice":
                    name = "设备报废、库存";
                    break;
                case "ChangeDealer":
                    name = "经销商变更";
                    break;
                case "DegradeStore":
                    name = "门店关闭、降级";
                    break;
                case "Transfer":
                    name = "设备三方转移";
                    break;
                case "BatchStore":
                    name = "批量变更门店主数据";
                    break;
                case "BatchDevice":
                    name = "批量变更设备主数据";
                    break;
                case "BatchContract":
                    name = "批量变更合同主数据";
                    break;
            }
            return name;
        }


        #region 自动发起流程

        /// <summary>
        /// 自动发起
        /// </summary>
        public static bool SendProcess(this TaskAPI TaskAPI, t_User UserAPI,
            string autoBusinessKey, string actions, string taskId, string summary)
        {
            var flag = false;

            try
            {
                TaskAPI taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                string applicationNo = Util.GenerateSequence(((object[])taskAPI["PrefixNo"])[0].ToString() + "-" + System.DateTime.Now.ToString("yyMM"), "", 4);

                taskAPI["ParentProcess"] = TaskAPI.Process;
                taskAPI["ParentIncident"] = TaskAPI.Incident;
                taskAPI["AutoBusinessKey"] = autoBusinessKey;
                taskAPI["BlankVlue"] = TaskAPI.GetVariableBySingleValue("BlankVlue");
                taskAPI["Actions"] = actions;
                taskAPI.InitTask(UserAPI, applicationNo);
                taskAPI.Summary = summary;

                taskAPI.SetStepRecipient();

                t_Assessment ass = TaskHelper.InitAssessment(taskAPI, UserAPI);

                flag = taskAPI.Send();

                if (flag)
                {
                    Storage.Save(Storage.Context1, ass);

                    (t_Assessment.process == taskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = taskAPI.Incident;
                    });
                }
            }
            catch (Exception ex)
            {
                flag = false;
                throw ex;
            }

            return flag;
        }

        #endregion
        
        /// <summary>
        /// 生成流程号
        /// </summary>
        /// <param name="taskApi"></param>
        /// <returns></returns>
        public static string GenerateApplicationNo(this TaskAPI taskApi)
        {
            return Util.GenerateSequence(((object[])taskApi["PrefixNo"])[0].ToString() + "-" + System.DateTime.Now.ToString("yyMM"), "", 4);
        }

        /*过滤TaskAPI.Summary st*/
        public static string getSummary(string summary)
        {
            string result = "";
            if (summary.Split('|').Count() > 0)
            {
                if (summary.Split('|')[0].Split('/').Count() > 1)
                {
                    result = summary.Split('|')[0].Split('/')[1];
                }
                else
                {
                    result = summary.Split('|')[0];
                }
            }
            else 
            {
                if (summary.Split('/').Count() > 1)
                {
                    result = summary.Split('/')[1];
                }
                else
                {
                    result = summary;
                }
            }

            return result.Trim();
        }
        /*过滤TaskAPI.Summary ed*/

        public static bool Abort(string taskId, string remark, string username)
        {
            string errormsg;
            bool flag = false;
            var task = new Task();
            task.InitializeFromTaskId(taskId);

            //加载实例信息
            var incident = new Incident();
            incident.LoadIncident(task.strProcessName, task.nIncidentNo);

            //执行任务取消
            flag = incident.AbortIncident(username, remark + " " + System.DateTime.Now.ToString(), out errormsg);

            errormsg = "";
            return flag;
        }

        /// <summary>
        /// 判断实例是否完成
        /// </summary>
        /// <param name="process"></param>
        /// <param name="incident"></param>
        public static bool IncidentIsFinish(string process, int incident)
        {
            Incident.Status status;

            var incdent = new Incident();
            incdent.LoadIncident(process, incident);
            incdent.GetIncidentStatus(out status);

            if (status.nIncidentStatus == IncidentStatuses.INCIDENT_STATUS_COMPLETED)
            {
                return true;
            }
            return false;
        }

        public static string GetTaskId(string process, int incident, string step)
        {
            string authority = HttpContext.Current.Request.Url.Authority;
            string url = "http://" + authority + "/pages/smd/ajaxtools/handler.ashx?action=get_task&p={0}&i={1}&s={2}";
            WebClient client = new WebClient();
            try
            {
                client.Encoding = System.Text.Encoding.UTF8;
                return client.DownloadString(string.Format(url, process, incident, step));
            }
            catch
            {
                return "error";
            }
        }

        public static Incident GetIncident(string process, int incidentNo)
        {
            var incident = new Incident();
            try
            {
                if (incident.LoadIncident(process, incidentNo))
                {
                    return incident;
                }
            }
            catch (Exception ex)
            {
                if (incident.LoadIncident(process, incidentNo))
                {
                    return incident;
                }
                return null;
            }

            return null;
        }
        public static string GetIncidentVariable(this Incident incident, string key)
        {
            object value;
            var strError = "";
            incident.GetVariableValue(key, out value, out strError);

            return value == null ? "" : value.ToString();
        }
    }
}